﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using UnityEngine.Networking.NetworkSystem;
using System.IO;


public enum eUI
{
    None,
    Start,
    Config,
    Login,
    RoleCreate,
    RoleSelect,
    Main,
    Function,
    Quests,
    TaskRewardDailyPop,
    TaskFinish,
    Dead,
    PopMsg,
    //  [EnumLabel("角色/背包")]
    Knapsack,
    GM,
    ItemTips,
    EquipTips,
    EquipTipsLeft,
    TaskKnapsack,
    Warehouse,
    Store,
    CellUnlock,
    ItemUse,
    GameSet,
    EquipAutoChange,
    MessageBox,
    //  [EnumLabel("角色/道行")]
    Tao,
    Map,
    //  [EnumLabel("角色/声望")]
    Prestige,
    // [EnumLabel("角色/技能")]
    Skill,
    // [EnumLabel("角色/人物")]
    Role,
    //  [EnumLabel("角色/人物属性")]
    RoleProperty,

    Dialogue,
    CutSceneDialogue,
    CutScene,

    //装备打造
    EquipForge,
    EquipForgeMain,
    EquipForgeMasterialBag,
    EquipIntensifyPL,
    EquipAdditionRefreshPL,
    EquipRefinePL,
    EquipPropertySwapPL,
    EquipForgeStarPL,
    EquipForgeCompoundPL,
    EquipForgeInheritPL,
    EquipForgeRecipe,
    EquipForgeTrepaningPL,
    EquipForgeInlayPL,
    EquipForgeRecyclePL,
    EquipForgeGemCompoundPL,
    ItemGetEffectCeShi,
    CommonBag,
    NewSkill,
    FuncOpen,
    Report,//捷报
    Noteic,//公告
    //好友相关
    Friend,
    FriendAndEmail,
    CommonList,
    InvitePlayer,
    TeamInvite,   //组队邀请
    TeamApply,   //入队申请
    AddFriend,
    Chat,
    ChatSetup,
    Fight,        //人物属性--战斗力界面
    FightText,    //战斗力跳动
    Information,   //其他玩家
    //拍卖行
    AuctionAndShop,
    Auction,
    AuctionSearch,
    Shop,         //商城
    ItemMove,
    Magic,  //法宝
    OpenMagic,   //法宝激活
    PetPL,
    Marriage,     //结婚
    Panel_Propose, //求婚
    EnterCopy,  //进入副本
    CopyQuene,  //副本排队
    CopyReward, //副本结算
    ItemUseBatch,
    LoginOut,      //退出角色
    Deblocking,    //背包仓库
    Welfare,
    GuideOfClick,//点击指引
    GameActivity,//活动
    GuideOfTouchMove,//滑动指引
    GuideOfClickTask,//任务指引
	GuideOfClickItem,//道具引导
    SelectRoleList,      //主场景点击人物列表
    Pay, //充值  主
    SchoolHonour,
    FirstCharge,         //首冲
    VIPPrivilege
}

enum eUILayer
{
    Middle,
    Top,
}

struct sUIInfo
{
    public string path;
    public eUILayer layer;

    public sUIInfo(string sPath, eUILayer eLayer)
    {
        path = sPath;
        layer = eLayer;
    }
}

public class UIManager : MonoBehaviour
{
    static UIManager instance;
    public static UIManager Instance
    {
        get
        {

            return instance;
        }
    }

    public Dictionary<eUI, UI_Base> UiEnable
    {
        get { return uiEnable; }
        set { uiEnable = value; }
    }

    public GameObject uiRoot;
    public UICamera uiCamera;

    Dictionary<eUI, sUIInfo> uiInfoDic = new Dictionary<eUI, sUIInfo>();
    Dictionary<eUI, UI_Base> uiDic = new Dictionary<eUI, UI_Base>();
    Dictionary<eUI, UI_Base> uiEnable = new Dictionary<eUI, UI_Base>(3);
    List<eUI> uiWithOutMask = new List<eUI>();

    struct UIQueue
    {
        public eUI type;
        public object arg;
        public UIQueue(eUI t, object a)
        {
            type = t;
            arg = a;
        }
    }
    List<UIQueue> uiQuene = new List<UIQueue>();
    void Awake()
    {
        instance = this;
        //Vector2 canvasSize = MainCanvas.GetComponent<RectTransform>().sizeDelta;
        //Layer_Top.GetComponent<RectTransform>().sizeDelta = canvasSize;
        //Layer_Middle.GetComponent<RectTransform>().sizeDelta = canvasSize;
        //Layer_Back.GetComponent<RectTransform>().sizeDelta = canvasSize;
        //DontDestroyOnLoad(MainCanvas);
        //DontDestroyOnLoad(Layer_Top);
        //DontDestroyOnLoad(Layer_Middle);
        //DontDestroyOnLoad(Layer_Back);
        DontDestroyOnLoad(uiRoot);
        DontDestroyOnLoad(UIManager.Instance.uiCamera.gameObject);

        uiWithOutMask.Add(eUI.Main);
        uiWithOutMask.Add(eUI.Knapsack);
        uiWithOutMask.Add(eUI.TaskKnapsack);
        uiWithOutMask.Add(eUI.Warehouse);
        uiWithOutMask.Add(eUI.EquipForge);
        uiWithOutMask.Add(eUI.EquipForgeMain);
        uiWithOutMask.Add(eUI.EquipForgeMasterialBag);
        uiWithOutMask.Add(eUI.EquipIntensifyPL);
        uiWithOutMask.Add(eUI.EquipAdditionRefreshPL);
        uiWithOutMask.Add(eUI.EquipPropertySwapPL);
        uiWithOutMask.Add(eUI.EquipForgeStarPL);
        uiWithOutMask.Add(eUI.EquipForgeCompoundPL);
        uiWithOutMask.Add(eUI.EquipForgeInheritPL);
        uiWithOutMask.Add(eUI.EquipForgeRecipe);
        uiWithOutMask.Add(eUI.EquipForgeTrepaningPL);
        uiWithOutMask.Add(eUI.EquipForgeInlayPL);
        uiWithOutMask.Add(eUI.EquipForgeRecyclePL);
        uiWithOutMask.Add(eUI.EquipForgeGemCompoundPL);
        uiWithOutMask.Add(eUI.EquipRefinePL);
        uiWithOutMask.Add(eUI.EquipAutoChange);
        uiWithOutMask.Add(eUI.PopMsg);
        uiWithOutMask.Add(eUI.CommonList);
        uiWithOutMask.Add(eUI.Auction);
        uiWithOutMask.Add(eUI.CommonBag);
        uiWithOutMask.Add(eUI.PetPL);
        uiWithOutMask.Add(eUI.ItemUseBatch);
        uiWithOutMask.Add(eUI.Deblocking);


    }

    private string noteicFile = "/NoticeConfig.txt";
    // Use this for initialization
    IEnumerator Start()
    {
        uiInfoDic.Add(eUI.VIPPrivilege, new sUIInfo("Prefab/NewUI/Friend/UIVIPPrivilege", eUILayer.Middle));
        ShowUI(eUI.Start);

        yield return null;
    }

    public GameObject GetUIRoot()
    {
        return uiRoot;
    }

    public bool IsShow(eUI e, bool checkActive = false)
    {
        if (!checkActive)
        {
            return uiEnable.ContainsKey(e);
        }
        return uiEnable.ContainsKey(e) && uiEnable[e].gameObject.activeInHierarchy;
    }

    public T GetUIBase<T>(eUI type) where T : UI_Base
    {
        if (uiDic.ContainsKey(type))
        {
            return uiDic[type] as T;
        }
        return null;
    }

    public UI_Base GetUI(eUI type, Transform parent = null, object arg = null)
    {
        if (uiDic.ContainsKey(type) && uiDic[type] == null)
        {
            uiDic.Remove(type);
        }


        UI_Base ui;
        if (HasUI(type))
        {
            ui = uiDic[type];
        }
        else
        {
            ui = CreateUI(type, arg);
            if (parent == null)
            {
                ui.transform.SetParent(uiRoot.transform);
            }
            else
            {
                ui.transform.SetParent(parent, false);
            }

        }
		EventManager.Instance.notify(EventManager.EventType.ET_UIOpen, type);
        return ui;
    }

    public bool HasUI(eUI type)
    {
        return uiDic.ContainsKey(type);
    }

    private UI_Base CreateUI(eUI type, object arg = null)
    {
        GameObject go = GameObject.Instantiate(Resources.Load(uiInfoDic[type].path)) as GameObject;
        if (go == null)
            Debug.LogError("没找到路径: " + uiInfoDic[type].path);

        UI_Base b = go.GetComponent<UI_Base>();
        if (b == null)
            Debug.LogError("没找到UI_Base: " + uiInfoDic[type].path);
        b.Init(arg);

        uiDic.Add(type, b);
        return b;
    }

    public GameObject GetUIObj(eUI type)
    {
        if (uiDic.ContainsKey(type))
        {
            if (null != uiDic[type])
                return uiDic[type].gameObject;
            else
                uiDic.Remove(type);
        }

        return null;
    }
    public UI_Base ShowUI(eUI type, object arg = null, bool showImmediately = true, bool addshade = true)
    {
        if (!showImmediately)
        {
#if Test_Common
			Debug.Log("进入队列: " + type);
#endif
            uiQuene.Add(new UIQueue(type, arg));
            if (uiQuene.Count > 1)
                return null;
        }
        if (uiDic.ContainsKey(type))
            return uiDic[type];

        Object g = Resources.Load(uiInfoDic[type].path);
        if (null == g)
        {
            Debug.LogError(uiInfoDic[type].path + " is not exit");
            return null;
        }
        GameObject go = GameObject.Instantiate(g) as GameObject;
        go.transform.SetParent(uiRoot.transform, false);

        UI_Base b = go.GetComponent<UI_Base>();

        if (b == null)
        {
            Debug.LogError("没有UI_Base " + uiInfoDic[type].path);
        }

        if (!b.Init(arg))
        {
            Debug.LogError("窗口初始化错误: " + type);
        }

        if (!showImmediately)
            b.bQueued = true;

        uiDic.Add(type, b);
        EventManager.Instance.notify(EventManager.EventType.ET_UIOpen, type);
        return b;
    }

    public void CloseUI(eUI type)
    {
        if (uiDic.ContainsKey(type) == false)
            return;

        UI_Base ui = uiDic[type];
        bool bQueued = ui.bQueued;

        uiEnable.Remove(type);
        uiDic.Remove(type);
        ui.OnClose();
        GameObject.Destroy(ui.gameObject);



#if Test_Common
        string str = "";
        for (int i = 0; i < uiQuene.Count; i++)
        {
            str += ", " + uiQuene[i].type;
        }

        if(bQueued)
            Debug.Log("关闭窗口: " + type + " 队列:" + bQueued + " 现在队列:" + uiQuene.Count + "  "+ str);
#endif

        if (bQueued && uiQuene.Count > 0)
        {
#if Test_Common
            Debug.Log("移除的窗口: " + uiQuene[0].type);
#endif
            uiQuene.RemoveAt(0);

            if (uiQuene.Count > 0)
            {
#if Test_Common
                Debug.Log("打开窗口: " + uiQuene[0].type);
#endif

                ShowUI(uiQuene[0].type, uiQuene[0].arg).bQueued = true;
            }
        }
    }

    public void CloseAllUI(bool bExceptMain = false)
    {
        UI_Base uiMain = null;
        if (bExceptMain)
        {
            uiMain = GetUI(eUI.Main);
            uiDic[eUI.Main] = null;
        }

        List<UI_Base> uis = new List<UI_Base>(uiDic.Values);
        uiDic.Clear();
        uiQuene.Clear();
        for (int i = 0; i != uis.Count; ++i)
        {
            if (uis[i] != null)
                GameObject.Destroy(uis[i].gameObject);
        }

        if (uiMain != null)
            uiDic[eUI.Main] = uiMain;
    }

    // 死亡 关闭其他界面
    public void CloseUIDead()
    {
        List<eUI> uis = new List<eUI>(uiDic.Keys);

        for (int i = 0; i != uis.Count; ++i)
        {
            bool bFind = false;
            for (int j = 0; j < uiQuene.Count; j++)
            {
                if (uiQuene[j].type == uis[i])
                {
                    bFind = true;
                }
            }
            if (bFind)
            {
                continue;
            }

            if (uis[i] != eUI.Main && uis[i] != eUI.PopMsg)
            {
                UI_Base ui = uiDic[uis[i]];
				if(null != ui)
                	GameObject.Destroy(ui.gameObject);
                uiDic.Remove(uis[i]);
            }
        }
    }


    public void AddMaskToUI(GameObject uiNode)
    {
        var g = Resources.Load("Prefab/UI/Panel_Mask");
        GameObject go = GameObject.Instantiate(g) as GameObject;
        go.transform.SetParent(uiNode.transform);
        go.transform.localPosition = Vector3.zero;
    }



    public void ShowUI_PopMsg(string text)
    {
        //UI_PopMsg pm = ShowUI(eUI.PopMsg) as UI_PopMsg;
        //if (null != pm)
        //{
        //    pm.ShowMsg(text);
        //}
    }

    public void HideDisplayUI(eUI type, bool b)
    {
        if (uiDic.ContainsKey(type) == false)
            return;
        UI_Base ui = uiDic[type];
        if (null == ui)
        {
            uiDic.Remove(type);
            return;
        }
        ui.gameObject.SetActive(b);
    }


    public void Release()
    {
        CloseAllUI();
    }


    //打开对话框
    public void Openadialogbox(int DiaID)
    {

#if Test_Common
        Debug.Log("打开对话框窗口" + DiaID);
#endif
        ShowUI(eUI.Dialogue, DiaID, false);
    }

    public void HideAllUI(bool show)
    {
        eUI[] uiArr = new eUI[uiDic.Keys.Count];
        uiDic.Keys.CopyTo(uiArr, 0);
        if (null == uiArr)
            return;
        foreach (eUI ui in uiArr)
        {
            HideDisplayUI(ui, show);
        }
    }

    public void HideAllUI(bool show, eUI notDisplayUI)
    {
        foreach (eUI ui in uiDic.Keys)
        {
            if (notDisplayUI == ui)
                continue;
            HideDisplayUI(ui, show);
        }
    }

    public void RemoveQueue(eUI uiType)
    {
        uiQuene.RemoveAll((UIQueue q) =>
        {
            return q.type == uiType;
        });
    }

	public UI_Base[] GetAllUI()
	{
		UI_Base[] uis = new UI_Base[uiDic.Count];
		uiDic.Values.CopyTo(uis, 0);

		return uis;
	}
}
